package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"recruit-pro/cache"
	"recruit-pro/models"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "10"))
	offset := (page - 1) * size
	var Count int64
	var life models.Life
	models.DB.Model(&life).Count(&Count)
	models.DB.Offset(offset).Limit(size).Find(&life).Order("created_at desc")
	redis_key := "recruit-pro_" + strconv.Itoa(int(life.ID))
	jsonData, _ := json.Marshal(&life)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"data": gin.H{
			"life":  life,
			"count": Count,
		},
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var life models.Life
	models.DB.Where("id=?", id).First(&life)
	redis_key := "recruit-pro_" + strconv.Itoa(int(life.ID))
	jsonData, _ := json.Marshal(&life)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"data": gin.H{
			"life": life,
		},
	})
	return
}

func Add(c *gin.Context) {
	title := c.Query("title")
	content := c.Query("content")
	var life = models.Life{
		Title:   title,
		Content: content,
	}
	err := models.DB.Create(&life)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "收藏失败",
		})
		return
	}
	redis_key := "recruit-pro_" + strconv.Itoa(int(life.ID))
	jsonData, _ := json.Marshal(&life)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "收藏成功",
	})
	return
}
